<!DOCTYPE html>
<html>
<head>
#include("../../_common/head.html")
<title>定时任务列表</title>
</head>
<body class="pear-container">
    <div class="layui-panel query-panel /*查询面板*/">
        <form id="main-form" class="layui-form layui-row layui-col-space16" lay-filter="main-form" onsubmit="return false;">
        	<div class="layui-col-xl2 layui-col-lg2 layui-col-md2 layui-col-sm3 layui-col-xs6">
				<div class="layui-input-wrap">
					<div class="layui-input-prefix">
						<i class="pear-icon pear-icon-text"></i>
					</div>
					<input type="text" name="word" value="#(word??)" placeholder="模糊查询" autocomplete="off" class="layui-input" lay-affix="clear">
				</div>
		    </div>
        	<div class="layui-col-xl2 layui-col-lg2 layui-col-md2 layui-col-sm3 layui-col-xs6">
				<div class="layui-input-wrap">
                    <select name="group">
                        <option value="">-- 任务分组 --</option>
                        #DICTS(type="job_group")
                        #for(item : dicts)
                        <option value="#(item.value)"#if(type?? == item.value) selected#end>#(item.label)</option>
                        #end
                    </select>
				</div>
		    </div>
            <div class="layui-col-xl2 layui-col-lg2 layui-col-md2 layui-col-sm3 layui-col-xs6">
                <div class="layui-btn-group">
                    <button id="main-form-search" type="button" class="layui-btn layui-btn-sm">
                        <i class="layui-icon layui-icon-search"></i> 搜索
                    </button>
                    <button id="main-form-reset" type="button" class="layui-btn layui-btn-sm layui-btn-primary">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                </div>
            </div>
        </form>
    </div>
    <div class="layui-panel data-panel /*数据面板*/">
        <table id="main-table"></table>
        <script id="main-pagebar" type="text/html">
        </script>
    </div>

<!-- 状态分组 -->
<script type="text/html" id="bean-jobGroup">
<!-- #DICTS(type="job_group")#for(item : dicts) -->
#[[{{# if(d.group == ']]##(item.value)#[[') { }}]]#
    <span class="#(item.listClass)">#(item.label)</span>
#[[{{# } }}]]#
<!-- #end -->
</script>

<!-- 状态字段 #set(isDisabled='disabled')#authPermissions('monitor:job:changeStatus')#set(isDisabled='')#end-->
<script type="text/html" id="bean-jobStatus">
    <input data-id= "{{ d.id }}" type="checkbox" lay-skin="switch" lay-filter="job_status" lay-text="启用|停用" #[[{{# if (d.status == "ON") { }}]]# checked#[[{{# } }}]]# value="{{ d.status }}" #(isDisabled)>
</script>

<!-- 创建时间 -->
<script type="text/html" id="bean-createdDatetime">
    {{layui.util.toDateString(d.createdDatetime, "yyyy-MM-dd HH:mm:ss")}}
</script>

#include("../../_common/data_table_template.html")
#include("../../_common/foot.html")

<script type="text/javascript">
layui.use(['jquery', 'form', 'dropdown'], () => {
    var $ = layui.jquery, form = layui.form, dropdown = layui.dropdown;

    //定义表格模块基本参数
    let module = {
        type: TABLE_TYPE.dataTable,             //表格类型：二维表格
        idField: 'id',                          //表格中 id 的字段名（与数据库定义的要一致，如userId）
        name: '数据字典',                        //表格模块的业务名称
        path: '#CTX()/admin/monitor/job/',      //表格模块的操作路径，以 '/' 结尾
    };

    //定义查询表单基本参数
    let queryForm = {
        id: 'main-form',                        //查询面板中 form 表单的 id 属性
        searchButtonId: 'main-form-search',     //查询面板中搜索按钮的 id 属性
        resetButtonId: 'main-form-reset',       //查询面板中重置按钮的 id 属性
    };

    //定义编辑对话框基本参数
    let editDialog = {
        submitFormId: 'edit-form',              //编辑页面（模态）中 form 表单的 ID 属性
        submitButtonId: 'submit-button',        //编辑页面（模态）中提交按钮的 ID 属性
        width: '720px',                         //对话框宽度
        height: '95%',                          //对话框高度
    };

    //定义表格操作基本参数
    let actions = {
        //#authPermissions('monitor:job:add')
        addFlag: true,                                      //新增记录权限标志
        addUrl: module.path + 'add',                        //新增记录 URL
        //#end
        //#authPermissions('monitor:job:edit')
        editFlag: true,                                     //修改记录权限标志
        editUrl: module.path + 'edit',                      //修改记录 URL
        //#end
        //#authPermissions('monitor:job:del')
        removeFlag: true,                                   //删除记录权限标志
        removeUrl: module.path + 'delete',                  //删除记录 URL
        batchRemoveFlag: true,                              //批量删除权限标志
        batchRemoveUrl: module.path + 'delete',             //批量删除 URL
        //#end
        //#authPermissions('monitor:job:query')
        detailFlag: true,                                   //查看记录详情权限标志
        detailUrl: module.path + 'detail',                  //查看记录详情 URL
        //#end
        //事件处理
        handleEvent: (options, event, obj) => {
            if (event == 'jobLog') {
                jobLog();
            }
        },
        //回调处理
        callbackEvent: (options, event, result) => {
        },
    };

    let toolbarButtons = '';
    //#authPermissions('monitor:jobLog:query')
    toolbarButtons = '<button class="pear-btn pear-btn-sm" plain lay-event="jobLog"><i class="pear-icon pear-icon-survey"></i>&nbsp;调度日志</button>';
    //#end

    let rowButtons = '';
    //#authPermissions('monitor:job:add', 'monitor:jobLog:query')
    rowButtons = '<button class="pear-btn pear-btn-xs" round plain id="more_{{d.id}}" data-id="{{d.id}}" data-name="{{d.name}}" data-group="{{d.group}}"><i class="layui-icon layui-icon-triangle-d"></i>&nbsp;更多</button>';
    //#end

    //定义数据表格的 options，参考：https://layui.dev/docs/2/table/#options
    let options = {
        id: 'main-table',                                               //设定实例唯一索引
        elem: '#main-table',                                            //绑定原始 table 元素
        title: module.name,                                             //定义 table 的大标题（在文件导出等地方会用到）
        url: module.path + 'query',                                     //发送异步请求的 URL
        initSort: {"field": "createdDatetime", "type": "desc"},         //初始排序状态
        toolbar: $.table.buildTableToolbar(actions, toolbarButtons),    //开启表格头部工具栏
        pagebar: '#main-pagebar',                                       //开启分页区域的自定义模板
        cols: [[                                                        //表头属性集
            {type: 'checkbox', align: 'center', width: 60},
            {field: 'name', align: 'left', minWidth: 150, width: '10%', sort: true, title: '任务名称'},
            {field: 'group', align: 'center', minWidth: 80, width: '10%', sort: true, title: '任务分组', templet: '#bean-jobGroup'},
            {field: 'target', align: 'left', minWidth: 150, width: '15%', title: '调用目标字符串'},
            {field: 'cron', align: 'left', minWidth: 150, width: '15%', title: '执行表达式'},
            {field: 'status', align: 'center', width: 110, sort: true, title: '任务状态', templet: '#bean-jobStatus'},
            {field: 'createdDatetime', align: 'center', width: 160, sort: true, title: '创建时间', templet: '#bean-createdDatetime'},
            {align: 'left', minWidth: 240, title: '操作', templet: $.table.buildRowToolbar(actions, rowButtons)},
        ]],
        done: (res, curr, count, origin) => {
            for (var i = 0; i < res.data.length; i++) {
                var data = [];
                //#authPermissions('monitor:job:add')
                data.push({title: "执行一次", menuId: 100, id: res.data[i].id});
                //#end
                //#authPermissions('monitor:jobLog:query')
                data.push({title: "调度日志", menuId: 101, id: res.data[i].id, name: res.data[i].name, group: res.data[i].group});
                //#end

                dropdown.render({
                    elem: '#more_' + res.data[i].id,
                    data: data,
                    id: '#more_' + res.data[i].id,
                    click: function(obj) {
                        if (obj.menuId == 100) {
                            // 执行一次
                            runOnce(obj.id);
                        }
                        if (obj.menuId == 101) {
                            // 调度日志
                            jobLog(obj.name, obj.group);
                        }
                    }
                });
            }
        },
        module: module,             //表格模块基本参数
        queryForm: queryForm,       //查询表单基本参数
        editDialog: editDialog,     //编辑对话框基本参数
        actions: actions,           //表格操作基本参数
    };

    let runOnce = (obj) => {
        $.modal.confirm('确认要立即执行一次任务吗？', (index) => {
            let url = module.path + "runOnce?id=" + obj;
            $.operate.save(url, {}, 'get');
        });
    };

    let jobLog = (name = '', group = '') => {
        top.layui.admin.closeTab("调度日志")
        top.layui.admin.jump("调度日志", "调度日志" , '#CTX()/admin/monitor/jobLog?word=' + name + "&group=" + group, false);
    }

    /*
     * 切换任务执行状态
     */
    form.on('switch(job_status)', function(data) {
        var value = data.elem.checked;
        var id = $(data.elem).attr("data-id");
        var tips = value ? "确定要 [启动] 定时任务？" : "确定要 [停用] 定时任务？";

        $.modal.confirm(tips, (index) => {
            let url = module.path + 'changeStatus';
            $.operate.save(url, {id: id, status: value}, 'put', (result) => {
                if(result.code != RESULT_CODE.SUCCESS) {
                    data.elem.checked = !value;
                    form.render('checkbox');
                }
            });
        }, (index) => {
            data.elem.checked = !value;
            form.render('checkbox');
        });
    });

    $(document).ready(() => {
        /**
         * 初始化数据表格
         */
        options = $.table.init(options);
    });

});
</script>

</body>
</html>
